// 路由注册与全局守卫：
// - Admin 域：/ 下的后台路由；User 域：/u 下的用户视图
// - meta.public 表示无需登录；其余路由需本地存在 userId/username 才允许访问
// - 登录后根据 sessionStorage.role 与 localStorage.preferredPanel 决定跳转
// 文件用途：路由注册与全局守卫（仅注释，不改逻辑）
// 路由域说明：
import { createRouter, createWebHistory } from 'vue-router'

// 路由表（按域划分）：
const routes = [
  {
    path: '/entry',
    name: 'roleEntry',
    component: () => import('@/views/RoleEntry.vue'),
    meta: { title: '选择入口' }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    meta: { public: true, title: '登录' }
  },
  {
    path: '/',
    component: () => import('@/layouts/AdminLayout.vue'),
    children: [
      { path: '', redirect: '/dashboard' },
    { path: 'dashboard', name: 'dashboard', component: () => import('@/views/Dashboard.vue'), meta: { title: '仪表盘', hasList: false } },
    { path: 'overview/company', name: 'companyOverview', component: () => import('@/views/overview/CompanyOverview.vue'), meta: { title: '公司概览', hasList: false } },
    { path: 'kanban', name: 'kanbanList', component: () => import('@/views/kanban/KanbanList.vue'), meta: { title: '看板列表', hasList: true } },
  { path: 'kanban/:id', name: 'kanbanDetail', component: () => import('@/views/kanban/KanbanDetail.vue'), meta: { title: '看板详情', hasList: false, parent: '/kanban' } },
    { path: 'schedule', name: 'scheduleList', component: () => import('@/views/schedule/ScheduleList.vue'), meta: { title: '日程列表', hasList: true } },
  { path: 'schedule/:id', name: 'scheduleDetail', component: () => import('@/views/schedule/ScheduleDetail.vue'), meta: { title: '日程详情', hasList: false, parent: '/schedule' } },
    { path: 'comments', name: 'commentList', component: () => import('@/views/comment/CommentList.vue'), meta: { title: '评论管理', hasList: true } },
    { path: 'users', name: 'userList', component: () => import('@/views/users/UserList.vue'), meta: { title: '用户管理', hasList: true } },
    { path: 'teams', name: 'teamList', component: () => import('@/views/teams/TeamList.vue'), meta: { title: '团队管理', hasList: true } },
  { path: 'worklogs', name: 'worklogList', component: () => import('@/views/worklog/WorklogList.vue'), meta: { title: '日志管理', hasList: true } },
  { path: 'worklogs/:id', name: 'worklogDetail', component: () => import('@/views/worklog/WorklogDetail.vue'), meta: { title: '日志详情', hasList: false, parent: '/worklogs' } },
    
    ]
  },
  {
    path: '/u',
    component: () => import('@/layouts/UserLayout.vue'),
    children: [
      { path: '', redirect: '/u/home' },
    { path: 'home', name: 'uHome', component: () => import('@/views/user/UHome.vue'), meta: { title: '首页', role: 'user', hasList: false } },
  { path: 'overview/leader', name: 'leaderOverview', component: () => import('@/views/overview/LeaderOverview.vue'), meta: { title: '我的概览', role: 'user', hasList: false } },
  { path: 'teams', name: 'uTeams', component: () => import('@/views/user/UTeams.vue'), meta: { title: '团队', role: 'user', hasList: false } },
  { path: 'teams/:id', name: 'uTeamDetail', component: () => import('@/views/user/UTeamDetail.vue'), meta: { title: '团队详情', role: 'user', hasList: false, parent: '/u/teams' } },
  { path: 'profile', name: 'uProfile', component: () => import('@/views/user/UProfile.vue'), meta: { title: '个人信息', role: 'user', hasList: false } },
    { path: 'schedules', name: 'uSchedules', component: () => import('@/views/user/USchedules.vue'), meta: { title: '日程', role: 'user', hasList: true } },
  { path: 'schedules/:id', name: 'uScheduleDetail', component: () => import('@/views/user/UScheduleDetail.vue'), meta: { title: '日程详情', role: 'user', hasList: false, parent: '/u/schedules' } },
    { path: 'kanban', name: 'uKanban', component: () => import('@/views/user/UKanban.vue'), meta: { title: '看板', role: 'user', hasList: false } },
  { path: 'kanban/:id', name: 'uKanbanDetail', component: () => import('@/views/user/UKanbanDetail.vue'), meta: { title: '看板详情', role: 'user', hasList: false, parent: '/u/kanban' } },
  { path: 'worklogs', name: 'uWorklogs', component: () => import('@/views/user/UWorklogs.vue'), meta: { title: '日志', role: 'user', hasList: true } },
  { path: 'worklogs/:id', name: 'uWorklogDetail', component: () => import('@/views/user/UWorklogDetail.vue'), meta: { title: '日志详情', role: 'user', hasList: false, parent: '/u/worklogs' } },
    ]
  },
  { path: '/:pathMatch(.*)*', name: 'notFound', component: () => import('@/views/NotFound.vue'), meta: { public: true, title: '未找到' } }
]

// 历史模式（可由 Vite BASE 控制二级路径部署）
// 历史模式（可由 Vite BASE 控制二级路径部署），保持与 Nginx SPA fallback 一致
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 判断是否为用户域路由（以 /u 开头）
function isUserDomain(path) {
  return path === '/u' || path.startsWith('/u/')
}

// 设置页面标题：按域拼接前缀（Admin/User）
router.afterEach((to) => {
  if (to.meta?.title) {
    const prefix = isUserDomain(to.path) ? 'User' : 'Admin'
    document.title = `${to.meta.title} - ${prefix}`
  }
})

// 访问控制：
// 1) public 路由直接放行
// 2) 未登录则统一跳转到 /login
// 3) admin 角色可进两域；若未设置偏好，先进 /entry 选择
// 4) 普通用户仅可访问 /u 域
// 访问控制逻辑：根据用户角色和登录状态进行路由访问权限控制
router.beforeEach((to) => {
  if (to.meta?.public) return true
  const uid = localStorage.getItem('userId')
  const username = localStorage.getItem('username')
  if (!uid || !username) {
    if (to.path !== '/login') return { path: '/login' }
    return true
  }
  const role = (sessionStorage.getItem('role') || '').toLowerCase()
  const preferred = localStorage.getItem('preferredPanel') // 'admin' | 'user'

  // 管理员：允许进入任何域；若无偏好，引导到入口选择页
  if (role === 'admin') {
    if (!preferred && to.path !== '/entry') return { path: '/entry' }
    if (to.path === '/login') {
      if (preferred === 'admin') return { path: '/dashboard' }
      if (preferred === 'user') return { path: '/u/home' }
      return { path: '/entry' }
    }
    if (to.path === '/' && preferred === 'user') return { path: '/u/home' }
    return true
  }

  // 非管理员：禁止访问后台域，仅允许 /u 下路由
  if (!isUserDomain(to.path)) {
    return { path: '/u/home' }
  }
  return true
})

export default router
